package opt_go

import (
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
	"time"
)

func goroutine_demo() {
	for i := 0; i < 100; i++ {
		println("i is", i)
		go runnable(&i)
	}
	time.Sleep(time.Second * 5)
}

// 拷贝变量不会有影响
func runnable(a *int) {

	fmt.Println("a value is ", a)
}

func go_sched() {

	for i := 0; i < 10; i++ {
		go func(str string) {

			for i := 0; i < 10; i++ {
				fmt.Println(i, "====", str)
			}
		}("world")
		// 放弃当前线程执行
		runtime.Gosched()
		fmt.Println("hello")

	}

}

func go_chan_go_9() {
	ints := make(chan int)
	go func() {
		for i := 0; i < 100; i++ {
			ints <- i
		}
		close(ints)
	}()
	count := 0
	for i := range ints {
		count++
		fmt.Println(i * i)
	}
	fmt.Println("=====count=====", count)
}

func timer_go_1() {
	// 定时器，延迟执行
	timer := time.NewTimer(2 * time.Second)
	now := time.Now()
	fmt.Println("start current time ", now.Format("2006-01-02 15:04:05"))
	// 阻塞2s
	t := <-timer.C
	fmt.Printf("current time %T   %v\n", t, t)
	/*	for t2 := range timer.C {
		fmt.Println(t2)
	}*/

	timer3 := time.NewTimer(2 * time.Second)
	<-timer3.C
	fmt.Println("=====2s run")
}

func ticker_new() {
	ticker := time.NewTicker(1 * time.Second)

	go func() {
		i := 0
		for {
			i++
			fmt.Println(<-ticker.C)
			if i == 3 {
				ticker.Stop()
			}
		}
	}()

	fmt.Println("=====finish===")
}

func go_chan_cache() {
	ints := make(chan int, 1)
	ints <- 100
	close(ints)
	for i := range ints {
		fmt.Println(i)
	}
}

func run_once() {
	var one sync.Once

	i := 0
	f := func() {
		i++
	}

	for i := 0; i < 10; i++ {
		go one.Do(f)
	}
	time.Sleep(1)
	fmt.Println(i)
}

func syncMap() {
	var group sync.WaitGroup
	syncMapVar := sync.Map{}
	group.Add(201)
	for i := 0; i < 200; i++ {
		go func(i int) {
			syncMapVar.Store(i, i*i)
			group.Done()
		}(i)
	}
	wg.Wait()

	i2 := int32(0)
	syncMapVar.Range(func(key, value any) bool {
		atomic.AddInt32(&i2, 1)
		fmt.Println("key is ", key, "value is ", value, " count is ", i2)
		return true
	})

}
